package it.unibo.mumu;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
//import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import it.unibo.mumu.entity.Universe;
import it.unibo.mumu.util.ListAdapter;
import it.unibo.mumu.util.ParseXmlUniverse;
import it.unibo.mumu.util.ParseXmlSelectedUniverse;
import it.unibo.mumu.util.Downloader;
import it.unibo.mumu.util.AddressUrl;

public class SelectUniverses extends Activity {
	
	ListAdapter boxAdapter;
    List<Universe> universes = null;
    AddressUrl addressUrl;
    private Context context;
	private boolean switching;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_select_universes);
		switching = false;
		addressUrl = new AddressUrl();
		
		doParse();
		
		Button btnCreateMultiverse = (Button) findViewById(R.id.btnCreateMultiverse);
		btnCreateMultiverse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	
            	if(switching)
					return;
				switching = true;
            	
		        ArrayList<Universe> checkArray = boxAdapter.getBox();
		        if(checkArray.size()>0 && checkArray.size()<4){
		        	
		        	String passIndex = "";
			        for (Universe p : boxAdapter.getBox()) {
			            if (p.getBox()){
//			              Log.i("RES", Integer.toString(p.getId()));
			              passIndex += Integer.toString(p.getId()) + "/";
//			              Log.i("PASSINDEX", passIndex);
			            }
			          }
			        
			        // estrarre ID dalla stringa
					final String[] separatedId = passIndex.split("/");
					
					addressUrl.addIdUniverseForXmlRequest(separatedId);
					
//					Toast.makeText(
//							getApplicationContext(),"Attendere. Download in corso...\nA breve disporrai del tuo Multiverso", Toast.LENGTH_LONG).show();
					AlertDialog.Builder builder = new AlertDialog.Builder(context,  AlertDialog.THEME_HOLO_DARK);
					builder.setMessage("A breve disporrai del tuo Multiverso").setTitle("Attendere. Download in corso");
					builder.setCancelable(false);
					
					AlertDialog dialog = builder.create();
					dialog.show();
	            	
					// scarica XML universi selezionati e zip relativi
					new Thread(new Runnable() {
			            public void run() {
			            	
			            	
			            	
			            	Downloader downloadXmlUniverses = new Downloader(context);
			            	downloadXmlUniverses.downloadResource(addressUrl.getUrl_XmlSelectedUniverse(), "universes.xml", getFilesDir().toString());
			            	
			            	ParseXmlSelectedUniverse parser = new ParseXmlSelectedUniverse();
			            	parser.parse(getFilesDir().toString());
			            	
			            	if(separatedId.length == 1){
			            		Downloader downloadAvatar = new Downloader(context);
			                	downloadAvatar.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[0]+".zip", separatedId[0]+".zip", getFilesDir().toString());
			            	}else if(separatedId.length == 2){
			            		Downloader downloadAvatar = new Downloader(context);
			            		Downloader downloadAvatar2 = new Downloader(context);
			                	downloadAvatar.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[0]+".zip", separatedId[0]+".zip", getFilesDir().toString());
			                	downloadAvatar2.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[1]+".zip", separatedId[1]+".zip", getFilesDir().toString());
			            	}else if(separatedId.length == 3){
			            		Downloader downloadAvatar = new Downloader(context);
			            		Downloader downloadAvatar2 = new Downloader(context);
			            		Downloader downloadAvatar3 = new Downloader(context);
			                	downloadAvatar.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[0]+".zip", separatedId[0]+".zip", getFilesDir().toString());
			                	downloadAvatar2.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[1]+".zip", separatedId[1]+".zip", getFilesDir().toString());
			                	downloadAvatar3.downloadResourceAndUnzip(addressUrl.getUrl_ZipResource()+separatedId[2]+".zip", separatedId[2]+".zip", getFilesDir().toString());
			            	}
			          
			            	
					        
				        	Intent toMyMultiverse = new Intent(SelectUniverses.this, StartActivity.class);
					        System.gc();
			            	finish();
			            	SelectUniverses.this.startActivity(toMyMultiverse);
			            	
			            	
			  	     }
			            
			            
			        }).start();
			        
			        
			        
		        }else{
		        	if(checkArray.size()<=0){
		        		Toast.makeText(getApplicationContext(), "Devi selezionare almeno un universo", Toast.LENGTH_SHORT).show();
		        	}else{
		        		Toast.makeText(getApplicationContext(), "Puoi selezionare al massimo 3 universi", Toast.LENGTH_SHORT).show();
		        	}
		        	switching = false;
		        }
		        
            }
        });
	}
	
	private void doParse(){
		
		try {
        	ParseXmlUniverse parser = new ParseXmlUniverse();
        	InputStream inputStream = openFileInput("universeList.xml");
            universes = parser.parse(inputStream);
            
            ArrayList<Universe> listUniverses = (ArrayList<Universe>) universes;
    		boxAdapter = new ListAdapter(this,(ArrayList<Universe>) listUniverses);

            ListView lvMain = (ListView) findViewById(R.id.lvMain);
            lvMain.setAdapter(boxAdapter);
            	            
        } catch (IOException e) {
            e.printStackTrace();
        }
}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.select_universes, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		Intent toHome = new Intent(SelectUniverses.this,
				StartActivity.class);
		
		System.gc();
		finish();
		startActivity(toHome);
	}

}

